import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'


//axios全局配置
import axios from 'axios'
//配置axios的全局基本路径
// axios.defaults.baseURL='http://localhost:8080/'
// axios.defaults.baseURL='http://api.pethome.com/'
axios.defaults.baseURL='http://api.yaohuaipeng.top/'

//为了后端校验是否已经登录，只要用axios的请求都要携带token
//=========*********=========//
axios.interceptors.request.use(config=>{
    let token = localStorage.getItem("token")
    if(token){
       config.headers["token"] = token;
    }
    return config;
},error => {
  Promise.reject(error)
})
//=========*********=========//
//后台如果没有登录或者权限会返回一个json错误，通过响应拦截器拦截这个错误，然后跳转到登录页面。
//=========*********=========//
axios.interceptors.response.use(config=>{
    if(!config.data.success && "noLogin"===config.data.message){
        localStorage.removeItem("token")
        localStorage.removeItem("user")
        router.push({ path: '/login' });
    }
    return config;
},error => {
    Promise.reject(error)
})
//=========*********=========//


// axios.defaults.baseURL='/api'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios


Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)


const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
    //放行
  if (to.path == '/login' || to.path == '/shopRegister') {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    next()
  }else{
      let user = JSON.parse(localStorage.getItem('user'));
      //判断是否登录
      if (!user) {
          //没有登录就跳转到登录
          next({ path: '/login' })
      } else {
          //如果登录了正常执行
          next()
      }
  }

})


new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

